import React, { Component } from 'react'
import {nanoid } from 'nanoid';
import './index.css';
import PubSub from 'pubsub-js';

export default class Header extends Component {
  constructor (props) {
    super(props);
    this.state = {
      value: ''
    };
  }
  handleKeyUp =(event) => {
    const {keyCode,target} = event;
    if (keyCode !== 13) return // 非回车
    if (target.value.trim() === '') {
      alert('请输入任务再提交');
      return;
    }
    //Enter按键按下，向Footer组件传值进行通信
    console.log('发布消息了')
    PubSub.publish('MYINPUT',target.value); //发布消息

    const todoObj = {id: nanoid(), name: target.value, done: false }
    this.props.addTodo(todoObj); //回调父组件传的函数
    target.value = '';
  }


  handleChange = (event) => {
    this.setState({
      value: event.target.value
    })
  }
  handleClick  = () => {
    const todoObj = {id: nanoid(), name: this.state.value, done: false }
    this.props.addTodo(todoObj)
    this.setState({
      value:''
    })
  }

  render() {
    return (
      <div>
         {/* <div className={header.top}>添加</div> */}
         {/* input为非受控组件,值为真实的DOM驱动 */}
         非受控组件: <input type="text" className="input" defaultValue="" placeholder='请输入任务名称，按回车键确认' onKeyUp={this.handleKeyUp}/>
          &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;
          {/* 受控组件,输入的值始终由React的state驱动 */}
          受控组件:<input type="text" className="input" placeholder="请输入" value={ this.state.value } onChange={ this.handleChange }/>
          <button onClick={this.handleClick }>  添加</button>
      </div> 
    )
  }
}
